package com.icehand.gateway.filter;

import com.icehand.common.code.SystemCode;
import com.icehand.common.constants.CommonConstants;
import com.icehand.common.result.BizResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author icehand
 */
public class AuthorizeGatewayFilter implements GatewayFilter, Ordered {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(CommonConstants.K_TOKEN);
        if (token == null) {
            token = request.getQueryParams().getFirst(CommonConstants.K_TOKEN);
        }

        if (StringUtils.isEmpty(token)) {
            return authFastFailResponse(exchange);
        }

        String authToken = (String) redisTemplate.opsForValue().get(token);
        if (authToken == null || !authToken.equals(token)) {
           return authFastFailResponse(exchange);
        }

        return chain.filter(exchange);
    }

    private Mono<Void> authFastFailResponse(ServerWebExchange exchange){
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(
                new BizResult(SystemCode.NOT_AUTH).toJSONString().getBytes(StandardCharsets.UTF_8));
        return exchange.getResponse().writeWith(Flux.just(buffer));
    }

    @Override
    public int getOrder() {
        return -10;
    }
}
